<template>
  <el-card>
    <!-- 搜索表单 -->
    <div class="search-input-group">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="顾客名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入顾客名称" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNum" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.orderStatus" placeholder="请选择订单状态" clearable>
            <el-option label="待支付" value="0"></el-option>
            <el-option label="已付款" value="1"></el-option>
            <el-option label="已收货" value="2"></el-option>
            <el-option label="已取消" value="3"></el-option>
            <el-option label="异常" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮组 -->
    <div class="btn-group">
      <el-button 
        v-if="btnGroup.editb" 
        type="success" 
        :icon="Edit"
        @click="showEditDialog"
        :disabled="multipleSelection.length !== 1"
      >
        修改
      </el-button>
      <el-button 
        v-if="btnGroup.deleteb" 
        type="danger" 
        :icon="Delete"
        @click="handleDelete"
        :disabled="multipleSelection.length <= 0"
      >
        删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="dataList" 
      style="width: 100%" 
      row-key="orderId"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" label="序号" width="80" show-overflow-tooltip />
      <!-- <el-table-column prop="orderId" label="订单ID" width="100" show-overflow-tooltip /> -->
      <el-table-column prop="orderNum" label="订单编号" show-overflow-tooltip />
      <el-table-column prop="customerName" label="顾客名称" width="150" show-overflow-tooltip />
      <el-table-column prop="productName" label="商品名称"show-overflow-tooltip />
      <el-table-column prop="orderStatus" label="订单状态" width="100" show-overflow-tooltip>
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
            {{ getOrderStatusText(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip />
      <el-table-column prop="updateTime" label="更新时间" width="180" show-overflow-tooltip />
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      :page-sizes="[10, 20, 50]"
      layout=" prev, pager, next"
      background
      @current-change="handleCurrentChange"
      class="pagination"
    />

     <!-- 修改对话框 -->
    <el-dialog
      title="修改订单"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        :model="operateDataForm"
        :rules="operateDataFormRules"
        ref="operateDataFormRef"
        label-width="100px"
      >
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="operateDataForm.orderStatus" placeholder="请选择订单状态">
            <el-option label="待支付" value="0"></el-option>
            <el-option label="已付款" value="1"></el-option>
            <el-option label="已收货" value="2"></el-option>
            <el-option label="已取消" value="3"></el-option>
            <el-option label="异常" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单描述" prop="orderDesc">
          <el-input 
            v-model="operateDataForm.orderDesc" 
            placeholder="请输入订单描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { getList, getSearchList, add, edit, remove } from "@/api/common/base"
import { onMounted, reactive, ref, computed } from "vue"
import { getOrderStatusText,getOrderStatusType } from '@/utils/DataTextMap'

// API 前缀
const API_PREFIX = "/admin/order"

// 对话框标题
const dialogTitle = computed(() => {
  return isEdit.value ? '修改订单' : '添加订单'
})

// 搜索表单
const searchForm = reactive({
  customerName: '',
  productName: '',
  orderNum: '',
  orderStatus: ''
})

// 对话框相关数据
const dialogVisible = ref(false)
const isEdit = ref(false)
const operateDataFormRef = ref(null)

// 修改数据表单
const operateDataForm = reactive({
  orderId: '',
  orderStatus: '',
  orderDesc: ''
})


// 表单验证规则
const operateDataFormRules = {
  orderStatus: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ],
  orderDesc: [
    { required: true, message: '请输入订单描述', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 数据列表相关
const dataList = ref([])
const multipleSelection = ref([])
const isSearch = ref(false)
const btnGroup = reactive({
  addb: false,
  editb: false,
  deleteb: false
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取数据列表
const getDataList = () => {
  let res = getList(API_PREFIX, pagination.currentPage)
  res.then(res => {
    dataList.value = res.data.records
    let opeStr = res.operateStr
    if (opeStr.includes("*") || opeStr.includes("a")) btnGroup.addb = true
    if (opeStr.includes("*") || opeStr.includes("d")) btnGroup.deleteb = true
    if (opeStr.includes("*") || opeStr.includes("u")) btnGroup.editb = true
    pagination.total = res.data.total
    pagination.pageSize = res.data.size
    pagination.currentPage = res.data.current
  })
}

// 搜索处理
const handleSearch = () => {
  isSearch.value = true
  let res = getSearchList(API_PREFIX, {
    customerName: searchForm.customerName,
    productName: searchForm.productName,
    orderNum: searchForm.orderNum,
    orderStatus: searchForm.orderStatus
  }, pagination.currentPage)
  res.then(res => {
    dataList.value = res.data.records
    pagination.total = res.data.total
    pagination.pageSize = res.data.size
    pagination.currentPage = res.data.current
  })
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.customerName = ""
  searchForm.productName = ""
  searchForm.orderNum = ""
  searchForm.orderStatus = ""
  isSearch.value = false
  getDataList()
}

// 显示修改对话框并填充 orderId
const showEditDialog = () => {
  // 确保只能选择一条记录进行修改
  if (multipleSelection.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行修改')
    return
  }

  // 获取选中的记录
  const selectedRow = multipleSelection.value[0]

  // 填充 orderId 到 operateDataForm
  Object.assign(operateDataForm, {
    orderId: selectedRow.orderId,
    orderStatus: selectedRow.orderStatus.toString(), // 确保状态值为字符串
    orderDesc: selectedRow.orderDesc || '' // 如果没有描述，默认为空字符串
  })

  // 显示对话框
  dialogVisible.value = true
}

const submitForm = () => {
  operateDataFormRef.value.validate(async (valid) => {
    if (valid) {
      const formData = {
        orderId: operateDataForm.orderId,
        orderStatus: parseInt(operateDataForm.orderStatus),
        orderDesc: operateDataForm.orderDesc
      }
      await edit(API_PREFIX, formData)
      dialogVisible.value = false
      refreshList()
    }
  })
}

// 删除操作
const handleDelete = async () => {
  pagination.currentPage = 1
  const ids = multipleSelection.value.map(item => item.orderId)
  await remove(API_PREFIX, { list: ids })
  refreshList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 当前页改变时触发
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  refreshList()
}

// 刷新列表
const refreshList = () => {
  if (isSearch.value) handleSearch()
  else getDataList()
}

onMounted(() => {
  getDataList()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  margin-bottom: 15px;
}

.btn-group .el-button {
  margin-right: 1px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.search-input-group {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-input-group .el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}
</style>